package com.example.sqliterecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private MySQLiteOpenHelper helper;
    private Button btn_add;
    private RecyclerView revStudent;
    private List<Student> studentList = new ArrayList<>();
    private studentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        helper = new MySQLiteOpenHelper(MainActivity.this,"stu.db",null,1);

        btn_add = findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });

        revStudent = findViewById(R.id.rcv_stu);
        readFromSQLite();
        adapter = new studentAdapter(MainActivity.this,studentList);
        revStudent.setAdapter(adapter);
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        revStudent.setLayoutManager(manager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        readFromSQLite();
        adapter.notifyDataSetChanged();
    }

    private void readFromSQLite() {
        studentList.clear();
        SQLiteDatabase readableDatabase = helper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("student", null, null, null, null, null, null);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
            String stuno = cursor.getString(0);
            String name = cursor.getString(1);
            int age = cursor.getInt(2);

            Student student = new Student(stuno, name, age);
            studentList.add(student);
        }
        cursor.close();
        readableDatabase.close();
    }
}